#include"apue.h"
typedef struct sockaddr* sp;
#define MAXMEN 10
#define MAX 255
int clifd[MAXMEN];
int sockfd;
void quit();//关闭服务器
void rcv_send(int n);//接收发送

int main()
{
	pthread_t tid;
	struct sockaddr_in src_addr={};
	socklen_t addr_len;
	char buf[MAX]={};
	//创建
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(0>sockfd)
	{
		perror("socket");
		return -1;
	}
	//准备地址
	struct sockaddr_in addr={AF_INET};
	addr.sin_port=htons(5566);
	addr.sin_addr.s_addr=inet_addr("192.168.2.3");
	//绑定
	int ret=bind(sockfd,(sp)&addr,sizeof(addr));
	if(0>ret)
	{
		perror("bind");
		return -1;
	}
	//设置排队数量
	listen(sockfd,1024);
	//创建一个线程关闭服务器
	pthread_create(&tid,NULL,(void*)&quit,NULL);
	//记录连接的人数将clifd赋值-1
	int i=0;
	for(i=0;i<MAXMEN;i++)
	{
		clifd[i]=-1;
	}
	//等待连接
	
	while(1)
	{
	
		addr_len=sizeof(src_addr);
		for (i = 0; i < MAXMEN; ++i)
		{
			
			if(clifd[i]==-1)
			{
				break;
			}
		}
		clifd[i]=accept(sockfd,(sp)&src_addr,&addr_len);
		sprintf(buf,"客户：%u",clifd[i]);
		printf("%s已上线！\n",buf);
		//创建线程处理消息
		pthread_create(malloc(sizeof(pthread_t)),NULL,(void*)&rcv_send,(void*)i);
	}
	return 0;
}

void quit()
{
	char msg[MAX]={};
	gets(msg);
	if(strcmp(msg,"q")==0)
	{
		printf("服务器已经关闭！\n");
		exit(0);
	}

}
void rcv_send(int n)
{
	char* msg="请输入你的名字：";
	char buf1[MAX];
	char buf2[MAX];
	char buf3[MAX];
	int i=0;

	char name[20];
	

	int len=write(clifd[n],msg,strlen(msg));
	if(len<0)
	{
		perror("write");
		return ;
	}
	len =read(clifd[n],name,sizeof(name));
	if(len>0)
	{
		name[len]=0;
	}
	//把该用户加入告诉其他用户
	strcpy(buf1,name);
	strcat(buf1,"加入悟空聊天室！");
	for(i=0;i<MAXMEN;i++)
	{
		if(clifd[i]!=-1)
		{
			write(clifd[i],buf1,strlen(buf1));
		}
	}
	//接收当前用户信息并转发给所有人
	while(1)
	{
		if((len=read(clifd[n],buf2,MAX))>0)
		{
			buf2[len]=0;
		}
		if(strcmp(buf2,"q")==0)
		{
			strcpy(buf3,name);
			strcat(buf3,"退出悟空聊天室！");
			
			for(i=0;i<MAXMEN;i++)
			{
				write(clifd[i],buf3,strlen(buf3));
			}
			close(clifd[n]);
			clifd[n]=-1;
			return;
		}
		strcpy(buf3,name);
		strcat(buf3,":");
		strcat(buf3,buf2);
		for(i=0;i<MAXMEN;i++)
		{
			if(clifd[i]!=-1)
			{
				write(clifd[i],buf3,strlen(buf3));
			}
		}
	}

}
